#!/usr/bin/env python  
# coding=utf-8

"""
小工具--PM导出


"""

import xlwt
import pymysql
from rest_framework.authentication import TokenAuthentication

from rest_framework.views import APIView
from backend.common.api_response import JsonResponse
import pytz
import xlwt
import pymysql
import datetime

fields_dict = {
    "prd_id": "产品线",
    "project_id": "项目编号",
    "project_name": "项目名称",
    "create_time": "提出日期",
    "summary": "项目概述",
    "vesion": "版本号",
    "origin": "商机获得方式",
    "introducer": "需求联系人",
    "priority": "分类（重点项目、总行或大金额项目、分行、其他）",
    "stage": "项目阶段",
    "status_currentweek": "状态",
    "master": "Master",
    "score": "分值",
    "contract_sign": "合同签署状态",
    "payment_percent": "回款比例",
    "company_audit": "公司审定会",
    "business_manager": "运营经理",
    "product_manager": "产品经理",
    "develop_manager": "技术经理",
    "test_manager": "测试经理",
    "partner": "合作/意向厂商及评价",
    "company_audit": "公司项目会",
    "budget": "项目预算（万元）",
    "date_online": "上线日期",
    "workload_plan": "计划人月数",
    "workload_put": "已投入人月数",
    "cycle_plan": "计划项目周期",
    "cycle_remanent": "还有多久上线",
    "content": "工作内容",
    "qa_currentweek": "本周问题/风险",
    "plan_nextweek": "下周计划",
    # "feasibility_analysis":"项目可行性、先进性分析",
    # "scope":"项目实施范围、实施方案",
    # "ro_analysis":"项目投入／产出分析",
    # "risk_analysis":"项目关键风险分析",
    "modify_time": "更新时间",
}
# prd_id 1  stage 13 status_currentweek 14
content = {1: {'1': "信贷体系", '2': "数字化运营", '3': "场景化体系", '4': "分行特色"},
           10: {'00': "初审", '01': "内审", '02': "公司审核", "03": "项目启动", "04": "需求设计", "05": "开发编码", "06": "SIT测试",
                "07": "UAT测试", "08": "生产试运行", "09": "投产发布", "10": "异常关闭"},
           11: {'00': "正常", '01': "提前", '02': "延迟", '03': "暂停"},
           4: {'': ""},
           14: {'00': "未签", '01': "已签"},
           }


def replace_value(value_list, jcs, ics, sheet):
    format = '%Y-%m-%d'
    for value in value_list:
        if jcs == value - 1 and results[ics - 1][jcs] != "" and results[ics - 1][jcs] is not None:
            repalce = results[ics - 1][jcs]
            if value == 4:
                ret = repalce.strftime(format)
            else:
                ret = content[value][repalce]
            # ret = content[value][repalce]
            sheet.write(ics, jcs, ret)
            break
        else:
            sheet.write(ics, jcs, results[ics - 1][jcs])
#
# conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='gaojingyu123', db='autotest',
#                        charset='utf8')
# conn = pymysql.connect(host='192.168.16.84', port=3308, user='kiton', passwd='*rrRou6xh4LSHYIQ', db='kiton',
#                        charset='utf8')
# cursor = conn.cursor()
# count = cursor.execute(
#     'select prd_id,project_id,project_name,create_time,summary,vesion,origin,introducer,priority,stage,status_currentweek,master,score,contract_sign,payment_percent,business_manager,product_manager,develop_manager,test_manager,partner,company_audit,budget,date_online,workload_plan,workload_put,cycle_plan,cycle_remanent,content,qa_currentweek,plan_nextweek,modify_time from project')
# # print(count)
# # 重置游标位置
# cursor.scroll(0, mode='absolute')
# # 搜取所有结果
# results = cursor.fetchall()
# # 测试代码，print results
# # 获取MYSQL里的数据字段
# fields = cursor.description
# # 将字段写入到EXCEL新表的第一行

def addEXcel():
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet('项目一览表', cell_overwrite_ok=True)
    for ifs in range(0, len(fields)):
        col = fields[ifs][0]
        fields_replace = fields_dict[col]
        sheet.write(0, ifs, fields_replace)
    ics = 1
    jcs = 0
    value_list = list(content.keys())
    value_list.sort()
    for ics in range(1, len(results) + 1):
        for jcs in range(0, len(fields)):
            replace_value(value_list, jcs, ics, sheet)



    tz = pytz.timezone('Asia/Shanghai')
    start_time = datetime.datetime.now(tz)

    format_start_time = start_time.strftime('%Y%m%d%H%M%S')
    # print(format_start_time)
    excelName = '项目管理表一览'+str(format_start_time)+'.xls'
    # print(excelName)

    wbk.save(excelName)
    cursor.close()
    return excelName



# if __name__ == '__main__':
#     print(11111)
#     addEXcel()
#     print(22222)

class DownloadPM(APIView):  # 常规

    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        interface_id = request.GET.get('interface_id')
        project_id = request.GET.get('project_id')

        """
        获取Api下载文档路径
        :param request:
        :return:
        """
        # 调用模板下载方法，成功返回模板路径，失败返回模板下载失败

        try:
            # print("进入方法")
            template = addEXcel()
            # print(template)
            if template == '失败':

                return JsonResponse(code="999997", msg="下载失败")
            else:
                return JsonResponse(code="999999", msg="下载成功", data=template)
            # return JsonResponse(data={'code': '999999', 'msg': '下载成功', 'data': template})
        except:
            return JsonResponse(code="999997", msg="下载失败")





